package com.xinxing.city.recovery.camea;

import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.IOException;

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback, Camera.AutoFocusCallback {
    private SurfaceHolder mHolder;
    private Camera mCamera;
    private Context context;
    private static final String TAG = CameraPreview.class.getSimpleName();

    public CameraPreview(Context context) {
        super(context);
        this.context = context;
        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        mHolder = getHolder();
        mHolder.addCallback(this);
        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, now tell the camera where to draw the preview.
        try {
            // 0: 启动后置摄像头,1:启动前置摄像头
            mCamera = Camera.open(0);

            setCameraParameters(mCamera);
            setCameraDisplayOrientation((Activity) context, 0, mCamera);
            mCamera.setPreviewDisplay(holder);
            mCamera.startPreview();
        } catch (IOException e) {
            Log.d(TAG, "Error setting camera preview: " + e.getMessage());
        }
    }

    /**
     *销毁视图时,释放内存
     */
    public void surfaceDestroyed(SurfaceHolder holder) {
        // empty. Take care of releasing the Camera preview in your activity.
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }

        Log.d("Dennis", "surfaceDestroyed() is called");
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // If your preview can change or rotate, take care of those events here.
        // Make sure to stop the preview before resizing or reformatting it.

        if (mHolder.getSurface() == null) {
            // preview surface does not exist
            return;
        }

        // stop preview before making changes
        try {
            mCamera.stopPreview();
        } catch (Exception e) {
            // ignore: tried to stop a non-existent preview
        }

        // set preview size and make any resize, rotate or
        // reformatting changes here

        // start preview with new settings
        try {
            setCameraParameters(mCamera);
            requestLayout();
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();

        } catch (Exception e) {
            Log.d(TAG, "Error starting camera preview: " + e.getMessage());
        }
    }

    public void setCameraParameters(Camera camera) {
        Camera.Parameters mCameraParameters = mCamera.getParameters();
        // 通常会默认在50Hz 如果设置60Hz会有水波纹
        mCameraParameters.setAntibanding(Camera.Parameters.ANTIBANDING_AUTO);
        boolean autoExposureLockSupported = mCameraParameters.isAutoExposureLockSupported();
        if (autoExposureLockSupported) {
            mCameraParameters.setAutoExposureLock(true);
        }
        // 设置闪光灯
        mCameraParameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
        // 设置颜色效果
        mCameraParameters.setColorEffect(Camera.Parameters.EFFECT_NONE);
        // 设置自动白平衡锁定状态
        mCameraParameters.setAutoWhiteBalanceLock(mCameraParameters.getAutoWhiteBalanceLock());
        // 设置曝光补偿指数
        // mCameraParameters.setExposureCompensation(1);
        mCameraParameters.setPreviewSize(1920, 1080);
        mCamera.setParameters(mCameraParameters);
    }

    public void takePicture(Camera.PictureCallback imageCallback) {
        mCamera.takePicture(null, null, imageCallback);
    }

    /**
     * 设置预览视图的方向 如果不设置的话,拍的照片方向不是我们看到的方向,通过这个方法,我们在旋转手机是,预览视图的方向也跟着旋转.
     *
     * @param activity
     * @param cameraId
     * @param camera
     */
    public void setCameraDisplayOrientation(Activity activity,
                                            int cameraId, android.hardware.Camera camera) {
        android.hardware.Camera.CameraInfo info =
                new android.hardware.Camera.CameraInfo();
        android.hardware.Camera.getCameraInfo(cameraId, info);
        int rotation = activity.getWindowManager().getDefaultDisplay()
                .getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }

        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {  // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }
        camera.setDisplayOrientation(result);
    }

    @Override
    public void onAutoFocus(boolean success, Camera camera) {

    }
}
